﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Data;

namespace RBAC.APP
{
    public class UserRole
    {
        #region Fields
        /// <summary>
        /// 用户点Id
        /// </summary>
        private string userId;
        /// <summary>
        /// 用户点Id
        /// </summary>
        public string UserId
        {
            get { return userId; }
            //set { userId = value; }
        }
        /// <summary>
        /// 该用户所有的角色array
        /// </summary>
        private ArrayList allRoleArray;
        /// <summary>
        /// 当前用户栏目
        /// </summary>
        private string currentDepartment;
        /// <summary>
        /// 当前用户栏目
        /// </summary>
        public string CurrentDepartment
        {
            get { return currentDepartment; }
        }
        #endregion Fields

        #region Constructor
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="userId">用户Id</param>
        public UserRole(string userId)
        {
            //赋值userId，并获得此userId的所有role。
            this.userId = userId;
            this.allRoleArray = new ArrayList();
            this.allRoleArray.Clear();
            this.allRoleArray = UserRole.GetAllRoleArrayofUser(userId);
        }
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="userId">用户Id</param>
        /// <param name="currentDepartment">当前栏目</param>
        public UserRole(string userId, string currentDepartment)
        {
            //赋值userId与当前Department
            this.userId = userId;
            this.currentDepartment = currentDepartment;
            this.allRoleArray = new ArrayList();
            this.allRoleArray.Clear();
            this.allRoleArray = UserRole.GetAllRoleArrayofUserDepartment(userId, currentDepartment);
        }
        #endregion Constructor

        #region NonstaticFunctions
        /// <summary>
        /// 当前用户的所有角色
        /// </summary>
        public List<Role> GetRoleofUser
        {
            get
            {
                if (string.IsNullOrEmpty(this.currentDepartment))
                    return UserRole.GetAllRoleofUser(this.userId);
                else
                    return UserRole.GetAllRoleofUserDepartment(this.userId, this.currentDepartment);
            }
        }
        /// <summary>
        /// 当前用户的所有角色列表
        /// </summary>
        public ArrayList GetRoleArrayofUser
        {
            get
            {
                if (string.IsNullOrEmpty(this.currentDepartment))
                    return UserRole.GetAllRoleArrayofUser(this.userId);
                else
                    return UserRole.GetAllRoleArrayofUserDepartment(this.userId, this.currentDepartment);
            }
        }

        /// <summary>
        /// 当前用户是否包含某个角色
        /// </summary>
        /// <param name="testRole">包含的某个角色</param>
        public bool HasRole(string testRole)
        {
            if (string.IsNullOrEmpty(testRole))
                return false;
            if (this.allRoleArray.Contains(testRole.Trim()))
                return true;
            return false;
        }

        /// <summary>
        /// 挑选某个角色
        /// </summary>
        /// <param name="role">角色Id</param>
        public UserDepartment this[string role]
        {
            get
            {
                if (string.IsNullOrEmpty(role)) return null;
                if (!HasRole(role)) return null;
                UserDepartment myUserDepartment = new UserDepartment(this.userId, role);
                return myUserDepartment;
            }
        }

        /// <summary>
        /// 为当前用户当前栏目添加角色
        /// </summary>
        /// <param name="newRole">需添加的角色Id</param>
        public int AddRole(string newRole)
        {
            //*****10321*****
            //向表SURD添加记录
            //（1）参数：userId：当前userId。
            //（2）参数：roleId：参数newRole。
            //（3）参数：departId：当前currentDepartment。（非常有可能此项不存在）
            //以上三者必须都存在（存在于相应的数据库中），且不能为空。否则返回103212.
            //（4）检测SURD表中，是否已有此记录。若已有，返回103213.
            //（5）向表：SURD中添加记录，成功返回103211，失败返回103219
            //--------------------------------------------------------
            //需Log的情况：103211，103219
            if (string.IsNullOrEmpty(userId))
                return 103212;
            if (string.IsNullOrEmpty(newRole))
                return 103212;
            if (string.IsNullOrEmpty(currentDepartment))
                return 103212;
            if (User.ReadUser(userId) == null)
                return 103212;
            if (Role.ReadRole(newRole) == null)
                return 103212;
            if (Department.ReadDepartment(currentDepartment) == null)
                return 103212;
            RBAC.ORM.DAL.SURD OptSURD = new ORM.DAL.SURD();
            DataSet ds = OptSURD.GetList("userID='" + userId + "' and roleID='" + newRole + "' and departID='" + currentDepartment + "'");
            if (ds.Tables[0].Rows.Count == 0)
            {
                RBAC.ORM.Model.SURD mySURD = new ORM.Model.SURD();
                mySURD.id = OptSURD.GetMaxId() + 1;
                mySURD.roleID = newRole;
                mySURD.userID = userId;
                mySURD.departID = currentDepartment;
                bool ok = OptSURD.Add(mySURD);
                if (ok)
                {
                    Operator.MakeLog(ObjectType.SURD, "103211" + currentDepartment);
                    return 103211;
                }
                else
                {
                    Operator.MakeLog(ObjectType.SURD, "103219" + currentDepartment);
                    return 103219;
                }
            }
            else
                return 103213;
        }

        /// <summary>
        /// 为当前用户当前栏目删除角色
        /// </summary>
        /// <param name="oldRole">需删除的角色Id</param>
        public int DeleteRole(string oldRole)
        {
            //*****10322*****
            //从表SURD中删除记录
            //（1）参数：userId：当前userId。
            //（2）参数：roleId：参数oldRole。
            //以上二者必须都存在，且不能为空。否则返回103222.
            //（3）参数：departId：当前currentDepartment。（非常有可能此项不存在）
            //          若currentDepartment不为空且存在，则删除表SURD中相应的一条记录。
            //                                             检测SURD表中，是否已有此记录。若没有，返回103223.
            //          若currentDepartment为空，则删除表：SURD中此用户此角色的所有记录。
            //                                             若在其中发生错误，返回103224
            //（4）成功返回103221，失败返回103229
            //--------------------------------------------------------
            //需Log的情况：103221，103229，103224
            RBAC.ORM.DAL.SURD OptSURD = new ORM.DAL.SURD();


            if (string.IsNullOrEmpty(userId))
                return 103222;
            if (string.IsNullOrEmpty(oldRole))
                return 103222;
            if (User.ReadUser(userId) == null)
                return 103222;
            if (Role.ReadRole(oldRole) == null)
                return 103222;
            if (string.IsNullOrEmpty(currentDepartment))
            {
                DataSet ds = OptSURD.GetList("userID='" + userId + "' and roleID='" + oldRole + "'");
                if (ds.Tables[0].Rows.Count == 0)
                {
                    Operator.MakeLog(ObjectType.SURD, "103229" + currentDepartment);
                    return 103229;
                }
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    bool ok = OptSURD.Delete(decimal.Parse(ds.Tables[0].Rows[i]["id"].ToString()));
                    if (!ok)
                    {
                        Operator.MakeLog(ObjectType.SURD, "103224" + currentDepartment);
                        return 103224;
                    }
                }
                Operator.MakeLog(ObjectType.SURD, "103221" + currentDepartment);
                return 103221;
            }
            else
            {
                DataSet ds = OptSURD.GetList("userID='" + userId + "' and roleID='" + oldRole + "' and departID='" + currentDepartment + "'");
                if (ds.Tables[0].Rows.Count == 0)
                    return 103223;
                bool ok = OptSURD.Delete(decimal.Parse(ds.Tables[0].Rows[0]["id"].ToString()));
                if (ok)
                {
                    Operator.MakeLog(ObjectType.SURD, "103221" + currentDepartment);
                    return 103221;
                }
                else
                {
                    Operator.MakeLog(ObjectType.SURD, "103229" + currentDepartment);
                    return 103229;
                }
            }
        }

        #endregion NonstaticFunctions

        #region StaticFunctions
        /// <summary>
        /// 获得某个用户的所有角色列表
        /// </summary>
        /// <param name="userId">用户Id</param>
        public static ArrayList GetAllRoleArrayofUser(string userId)
        {
            //根据SURD表，获得某个用户的所有RoleId，所得结果放入Arraylist，按照RoleId升序排列
            //参数不能为空，判定用户是否存在，用户不存在直接返回null。
            if (string.IsNullOrEmpty(userId))
                return null;
            else
            {
                if (User.ReadUser(userId) == null)
                    return null;
                ArrayList myArrayList = new ArrayList();
                RBAC.ORM.DAL.SURD OptSURD = new ORM.DAL.SURD();
                DataSet ds = OptSURD.GetList("userID='" + userId + "'");
                if (ds.Tables[0].Rows.Count == 0)
                    return null;
                else
                {
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        if (myArrayList.Contains(ds.Tables[0].Rows[i]["roleID"].ToString()))
                            continue;
                        myArrayList.Add(ds.Tables[0].Rows[i]["roleID"].ToString());
                    }
                    return myArrayList;
                }
            }

        }
        /// <summary>
        /// 获得某个用户的所有角色
        /// </summary>
        /// <param name="userId">用户Id</param>
        public static List<Role> GetAllRoleofUser(string userId)
        {
            //调用函数GetAllRoleArrayofUser，将返回结果制成Role对象泛型返回
            //参数不能为空，判定用户是否存在，用户不存在直接返回null。
            if (string.IsNullOrEmpty(userId))
                return null;
            else
            {
                if (User.ReadUser(userId) == null)
                    return null;
                List<Role> myListRole = new List<Role>();
                ArrayList myArrayList = new ArrayList();
                myArrayList = UserRole.GetAllRoleArrayofUser(userId);
                if (myArrayList == null)
                    return null;
                else
                {
                    for (int i = 0; i < myArrayList.Count; i++)
                    {
                        myListRole.Add(Role.ReadRole(myArrayList[i].ToString()));
                    }
                    return myListRole;
                }

            }
        }
        /// <summary>
        /// 获得某个用户某个栏目下的所有角色列表
        /// </summary>
        /// <param name="userId">用户Id</param>
        /// <param name="departmentId">栏目Id</param>
        public static ArrayList GetAllRoleArrayofUserDepartment(string userId, string departmentId)
        {
            //根据SURD表，获得某个用户某个栏目下的所有RoleId，所得结果放入Arraylist，按照RoleId升序排列
            //参数不能为空，判定用户与栏目是否存在，若有一个不存在，直接返回null。
            if (string.IsNullOrEmpty(userId))
                return null;
            else if (string.IsNullOrEmpty(departmentId))
                return null;
            else
            {
                if (User.ReadUser(userId) == null)
                    return null;
                else if (Department.ReadDepartment(departmentId) == null)
                    return null;
                else
                {
                    RBAC.ORM.DAL.SURD OptSURD = new ORM.DAL.SURD();
                    ArrayList myArrayList = new ArrayList();
                    DataSet ds = OptSURD.GetList("userID='" + userId + "' and departID='" + departmentId+"' order by roleID asc");
                    if (ds.Tables[0].Rows.Count == 0)
                        return null;
                    else
                    {
                        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                        {
                            if (myArrayList.Contains(ds.Tables[0].Rows[i]["roleID"].ToString()))
                                continue;
                            myArrayList.Add(ds.Tables[0].Rows[i]["roleID"].ToString());
                        }
                        return myArrayList;
                    }
                }
            }
        }
        /// <summary>
        /// 获得某个用户某个栏目下的所有角色
        /// </summary>
        /// <param name="userId">用户Id</param>
        /// <param name="departmentId">栏目Id</param>
        public static List<Role> GetAllRoleofUserDepartment(string userId, string departmentId)
        {
            //调用函数GetAllRoleArrayofUserDepartment，将返回结果制成Role对象泛型返回
            //参数不能为空，判定用户与栏目是否存在，若有一个不存在，直接返回null。
            if (string.IsNullOrEmpty(userId))
                return null;
            else if (string.IsNullOrEmpty(departmentId))
                return null;
            else
            {
                if (User.ReadUser(userId) == null)
                    return null;
                else if (Department.ReadDepartment(departmentId) == null)
                    return null;
                else
                {
                    List<Role> myListRole = new List<Role>();
                    ArrayList myArrayList = new ArrayList();
                    myArrayList = UserRole.GetAllRoleArrayofUserDepartment(userId, departmentId);
                    if (myArrayList == null)
                        return null;
                    else
                    {
                        for (int i = 0; i < myArrayList.Count; i++)
                        {
                            myListRole.Add(Role.ReadRole(myArrayList[i].ToString()));
                        }
                        return myListRole;
                    }
                }
            }
        }
        #endregion StaticFunctions
    }
}
